<script lang="ts" setup>
import { usePrice } from '~/util'
import { useProvider, getPairInfoBatch } from '~/util/ethers_manager'
import { trackingList } from '~/config/trackingList.json'
import { ethers } from 'ethers'



import Highlight from '~/components/Highlight.vue'

import themeManager from "~/util/theme_manager";
const theme = themeManager.getTheme()

const key = 'etherManager_ankxlfcuhusnfakhmxdgkns'

const WETH_ADDRESS = ethers.utils.getAddress('0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2')

const USED_BASE = [
  'ETH',
  'USDT',
]

const USED_CASH = [
  { name: 'CNY', symbol: '¥' },
  { name: 'USD', symbol: '$' },
]

const _calcPrice = (item: any, basePrice: any) => {
  if (!basePrice) return '-'
  const reserveWETH = parseFloat(item.token0Addr == WETH_ADDRESS ? item.reserve0 : item.reserve1)
  const reserveToken = parseFloat(item.token0Addr == WETH_ADDRESS ? item.reserve1 : item.reserve0)
  return (basePrice * reserveWETH / reserveToken).toFixed(2)
}

function getTrackingList() {
  const trackingList_str = localStorage.getItem('trackingList')
  if (!trackingList_str) {
    return trackingList
  }
  else {
    return JSON.parse(trackingList_str)
  }
}

const basePrices = ref(null as any)

const profile = ref(getTrackingList().filter((item: any) => item.name == 'Mainnet')[0])
const listdata = ref([] as any[])
const firstFinish = ref(false)
const ethersManager = ref(null as any)

const calcLink = (item: any) => {
  const addr = item.token0 == 'WETH' ? item.token1Addr : item.token0Addr
  return `${profile.value.scan}/address/${addr}`
}

const getData = async () => {

  const res = await getPairInfoBatch(
    profile.value.multicall,
    useProvider(profile.value.provider).provider,
    profile.value.pairs.map((item: any) => item.address)
  )

  listdata.value = res.map(item => {
    return {
      ...item,
      name: item.token0 == 'WETH' ? item.token1 : item.token0,
      baseName: item.token0 == 'WETH' ? item.token0 : item.token1,
      reserveToken: parseFloat(item.token0Addr == WETH_ADDRESS ? item.reserve1 : item.reserve0),
      reserveWETH: parseFloat(item.token0Addr == WETH_ADDRESS ? item.reserve0 : item.reserve1),
      prices: {}
    }
  })
  firstFinish.value = true
}

const startGetData = () => {
  getData()
  window.setInterval(getData, 10000)
}

const getPrice = async () => {
  const _basePrices = {}
  const _ts = [] as any[]
  USED_BASE.forEach(base => {
    USED_CASH.forEach(cash => {
      _ts.push(usePrice(base, cash.name))
    })
  })
  const res = await Promise.all(_ts)
  USED_BASE.forEach((base, i) => {
    (_basePrices as any)[base] = {}
    USED_CASH.forEach((cash, j) => {
      (_basePrices as any)[base][cash.name] = res[i * USED_CASH.length + j]
    })
  })
  basePrices.value = _basePrices
}

const init = async () => {
  getPrice()
    ; (window as any)[key] = useProvider(profile.value.provider)
  startGetData()
}

const calcPriceAll = () => {
  if (!basePrices.value) return
  for (let i = 0; i < listdata.value.length; i++) {
    let priceObj = listdata.value[i].prices
    for (const cash of USED_CASH) {
      const baseName = listdata.value[i].baseName == 'WETH' ? 'ETH' : listdata.value[i].baseName
      const basePrice = basePrices.value[baseName][cash.name]
      priceObj[cash.name] = _calcPrice(listdata.value[i], basePrice)
    }
  }
}

watch(listdata, () => {
  calcPriceAll()
})

watch(basePrices, () => {
  calcPriceAll()
})

onMounted(() => {
  init()
})
</script>

<template>
  <div id="page-pricelist" :style="{ background: theme.getColor(2) }">
    <div :style="themeManager.paneTransparentStyle()">Price List</div>
    <div :style="themeManager.paneTransparentStyle()">Off-chain</div>
    <table class="table-g" :style="themeManager.paneStyle()">
      <tr>
        <th class>Name</th>
        <th
          class="text-right"
          v-for="(item, index) in USED_CASH"
          :key="index"
        >Price({{ item.symbol }})</th>
      </tr>
      <tr v-for="(item, index) in USED_BASE" :key="index">
        <td class="mx-4 text-monospace">{{ item }}</td>
        <td
          class="mx-4 text-right text-monospace"
          v-for="(item2, index2) in USED_CASH"
          :key="index2"
        >
          <span v-if="!basePrices">-</span>
          <Highlight v-else :num="basePrices[item][item2.name].toString()" />
        </td>
      </tr>
    </table>
    <div :style="themeManager.paneTransparentStyle()">On-chain</div>
    <div v-if="!firstFinish" class="mb-3" :style="themeManager.paneStyle()">getting price...</div>
    <table v-if="firstFinish" :style="themeManager.paneStyle()" class="table-g">
      <tr>
        <th class>Token-Base</th>
        <th class="text-right">Reserve Token</th>
        <th class="text-right">Reserve Base</th>
        <th
          class="text-right"
          v-for="(item, index) in USED_CASH"
          :key="index"
        >Price({{ item.symbol }})</th>
      </tr>
      <tr v-for="(item, index) in listdata" :key="index">
        <td class="mx-4 text-monospace">
          <a :href="calcLink(item)" target="_blank" class="link-no-deco">
            <Highlight :num="`${item.name}-${item.baseName}`" sep="-" />
          </a>
        </td>
        <td class="mx-4 text-right text-monospace">
          <Highlight :num="item.reserveToken.toString()" />
        </td>
        <td class="mx-4 text-right text-monospace">
          <Highlight :num="item.reserveWETH.toString()" />
        </td>
        <td
          class="mx-4 text-right text-monospace"
          v-for="(item2, index2) in USED_CASH"
          :key="index2"
        >
          <span v-if="!basePrices">-</span>
          <Highlight v-else :num="item.prices[item2.name].toString()" />
        </td>
      </tr>
    </table>
  </div>
</template>

<style scoped>
#page-pricelist {
  height: calc(100vh - 49px);
  overflow: auto;
  flex: 1;
  padding: 1rem;
}
.table-g {
  width: 100%;
  margin-bottom: 1rem;
}

thead th {
  vertical-align: bottom;
}
td,
th {
  padding: 0.75rem;
  vertical-align: top;
  border-top: 1px solid #dee2e6;
}
th {
  border: none;
}
</style>